﻿using NicoView.Model.Service;
using NicoView.Model.Share.Speech;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NicoView.Model.Speech
{
    public sealed class NicoSpeechServiceApplication : NicoViewObservableObject, IDisposable
    {
        public NicoSpeechServiceApplication(NicoViewSpeacherApplication app)
        {
            
            _baseApplication = app;
            ProviderList = new ObservableCollection<SpeacherProviderBase>();
            foreach(SpeacherProviderBase provider in app.ProviderList)
            {
                ProviderList.Add(provider.Copy());
            }

            CurrentSpeacherProvider = app.CurrentSpeacherProvider;
        }

        private ISpeacherProvider _currentSpeacherProvider;
        public ISpeacherProvider CurrentSpeacherProvider
        {
            get
            {
                return _currentSpeacherProvider;
            }
            set
            {
                if (_currentSpeacherProvider == value) return;
                _currentSpeacherProvider = value;
                RaisePropertyChanged("CurrentSpeacherProvider");
            }
        }
        public ObservableCollection<SpeacherProviderBase> ProviderList { get; set; }
        

        public async Task SpeechAsync(SynthesizeArgs args)
        {
            await Task.Factory.StartNew(() =>
            {
                lock (CurrentSpeacherProvider) lock (_baseApplication.ProviderList)
                    {
                        if (_enable)
                        {
                            if (CurrentSpeacherProvider != null)
                            {

                                CurrentSpeacherProvider.GetInstance().Speech(args);
                            }
                        }
                    }

            });

        }

        private bool _enable;

        public void SpeechStart()
        {
            _enable = true;
        }

        public void SpeechCancel()
        {
            _enable = false;
            foreach (var speacher in ProviderList)
            {
                if (speacher.Created)
                {
                    speacher.GetInstance().SpeechCancel();
                }
            }


        }

        public void Dispose()
        {
            SpeechCancel();
            lock (ProviderList)
            {
                foreach (var speacher in ProviderList)
                {
                    if (speacher.Created)
                    {

                        speacher.GetInstance().Dispose();

                    }
                }
            }
        }
        

        private NicoViewSpeacherApplication _baseApplication;
    }
}
